using MaterialDesignColors;
using MaterialDesignColors.ColorManipulation;
using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serilog;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using WpfMvvmTemplate.MD.Common;
using WpfMvvmTemplate.MD.ViewModels.Main;
using WpfMvvmTemplate.MD.Views.Dialogs;
using WpfMvvmTemplate.MD.Views.Windows;

namespace WpfMvvmTemplate.MD.Views.Main
{
    public partial class MainWindowView
    {
        public MainWindowView()
        {
            InitializeComponent();

            skinBtn.Click += (s, e) => App.Current.Services.GetService<SkinWindowView>()!.ShowDialog();

            //弹框
            MainSnackbar.MessageQueue?.Enqueue("Welcome to Material Design In XAML Toolkit");

        }

        #region 主题，颜色，左右，中英文设置

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //读取文件内容
            string fileContent = File.ReadAllText(GlobalStaticData.AppSettingsFilePath);

            //解析文件内容
            JObject? jObject = JObject.Parse(fileContent);

            PaletteHelper paletteHelper = new();
            ITheme theme = paletteHelper.GetTheme();

            //主题
            switch(jObject?["AppSettings"]?["Theme"]!.ToString())
            {
                case "0":
                    theme.SetBaseTheme(new MaterialDesignLightTheme());
                    paletteHelper.SetTheme(theme);
                    DarkModeToggleButton.IsChecked = false;
                    break;

                case "1":
                    theme.SetBaseTheme(new MaterialDesignDarkTheme());
                    paletteHelper.SetTheme(theme);
                    DarkModeToggleButton.IsChecked = true;
                    break;
            }

            //颜色
            string selectedBrushValue = jObject?["AppSettings"]?["SelectedBrush"]?.Value<string>()!;
            Color hue = (Color)ColorConverter.ConvertFromString(selectedBrushValue);
            theme.PrimaryLight = new ColorPair(hue.Lighten());
            theme.PrimaryMid = new ColorPair(hue);
            theme.PrimaryDark = new ColorPair(hue.Darken());
            paletteHelper.SetTheme(theme);

            //加载中英文
            GlobalStaticData.LanguageNum = (int)(jObject?["AppSettings"]?["Language"]!);
            ComMethod.LanguageWinDicHelper(GlobalStaticData.LanguageNum, this);

            //加载语言切换按钮
            LangsToggleButton.IsChecked = GlobalStaticData.LanguageNum == 0 ? false : true;

            //清空搜索关键字
            MenuToggleButton.Click += (s, e) =>
            {
                App.Current.Services.GetService<MainWindowViewModel>()!.SearchKeyword = string.Empty;
            };
        }

        /// <summary>
        /// 切换黑白主题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuDarkModeButton_Click(object sender, RoutedEventArgs e)
        {
            var paletteHelper = new PaletteHelper();
            var theme = paletteHelper.GetTheme();
            IBaseTheme baseTheme = new MaterialDesignLightTheme();

            //读取文件内容
            string fileContent = File.ReadAllText(GlobalStaticData.AppSettingsFilePath);
            JObject? jObject = JObject.Parse(fileContent);

            JToken? jToken = jObject?["AppSettings"]?["Theme"];

            switch(DarkModeToggleButton.IsChecked)
            {
                case true:
                    baseTheme = new MaterialDesignDarkTheme();
                    jToken?.Replace(JToken.FromObject("1"));
                    break;

                case false:
                    baseTheme = new MaterialDesignLightTheme();
                    jToken?.Replace(JToken.FromObject("0"));
                    break;
            }

            theme.SetBaseTheme(baseTheme);
            paletteHelper.SetTheme(theme);

            //保存中英文到配置文件中
            File.WriteAllText(GlobalStaticData.AppSettingsFilePath, jObject?.ToString());
        }

        /// <summary>
        /// 左右方向
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FlowDirectionButton_Click(object sender, RoutedEventArgs e)
        {
            FlowDirection = FlowDirectionToggleButton.IsChecked.GetValueOrDefault(false) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
        }

        /// <summary>
        /// 显示对话框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void MenuPopupButton_OnClick(object sender, RoutedEventArgs e)
        {
            var sampleMessageDialog = new SampleMessageDialog
            {
                Message = { Text = ((ButtonBase)sender).Content.ToString() },
                AcceptBtn = { Content = GlobalStaticData.LanguageDic["Accept"] }
            };

            await DialogHost.Show(sampleMessageDialog, "RootDialog");
        }

        /// <summary>
        /// 鼠标左键抬起时，关闭菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UIElement_OnPreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var dependencyObject = Mouse.Captured as DependencyObject;

            while(dependencyObject != null)
            {
                if(dependencyObject is ScrollBar) return;
                dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
            }

            MenuToggleButton.IsChecked = false;

            //清空搜索关键字
            App.Current.Services.GetService<MainWindowViewModel>()!.SearchKeyword = string.Empty;
        }

        private void OnSelectedItemChanged(object sender, DependencyPropertyChangedEventArgs e) => MainScrollViewer.ScrollToHome();

        private void MenuToggleButton_OnClick(object sender, RoutedEventArgs e) => DemoItemsSearchBox.Focus();

        /// <summary>
        /// 语言切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void LangsToggleButton_Click(object sender, RoutedEventArgs e)
        {
            //读取文件内容
            string fileContent = File.ReadAllText(GlobalStaticData.AppSettingsFilePath);
            JObject? jObject = JObject.Parse(fileContent);

            //解析文件内容
            JToken? jToken = jObject?["AppSettings"]?["Language"];

            //修改Language的值
            int res = LangsToggleButton.IsChecked == false ? 0 : 1;
            jToken?.Replace(JToken.FromObject(res.ToString()!));

            //保存中英文到配置文件中
            File.WriteAllText(GlobalStaticData.AppSettingsFilePath, jObject?.ToString());

            GlobalStaticData.LanguageNum = res;
            ComMethod.LanguageWinDicHelper(GlobalStaticData.LanguageNum, this, false);

            //提示弹框
            //MessageBox.Show(GlobalStaticData.LanguageDic["Switch languages after software restart!"], GlobalStaticData.LanguageDic["tisps2"]);

            var sampleMessageDialog = new SampleMessageDialog
            {
                Message = { Text = GlobalStaticData.LanguageDic["Switch languages after software restart!"] },
                AcceptBtn = { Content = GlobalStaticData.LanguageDic["Accept"] }
            };

            await DialogHost.Show(sampleMessageDialog, "RootDialog");

        }

        #endregion

    }
}